<template>
  <div>
    <div class="logo">
      <img src="../../assets/logo.png" alt="">
    </div>
    <div class="erweima">
      <h1>扫码登录</h1><br>
      <button  v-on:click="create_erweima">点我生成二维码</button>
      <br>
      <div class="rightb">使用&nbsp;<a href="https://music.163.com/#/download" style="color:skyblue">网易云app</a>
        扫码登录</div>
      <img id="qrImg" src="" class="erweima">
    </div>

  </div>
</template>
<script>
export default {
  name: 'APP',
  data() {
    return {
      url: "http://localhost:3000/login/status?timestamp=${Date.now()}",

    }
  },
  methods: {
    async checkStatus(key) {
      const res = await this.axios({
        url: `http://localhost:3000/login/qr/check?key=${key}&timerstamp=${Date.now()}`,
      })
      return res.data
    },
    async getLoginStatus(cookie = '') {
      const res = await this.axios({
        url: `http://localhost:3000/login/status?timerstamp=${Date.now()}`,
        method: 'post',
        data: {
          cookie,
        },
      })
      console.log(JSON.stringify(res.data, null, 2));

    },
    async login() {
      let timer
      let timestamp = Date.now()
      const cookie = localStorage.getItem('cookie')
      this.getLoginStatus(cookie)
      const res = await this.axios({
        url: `http://localhost:3000/login/qr/key?timerstamp=${Date.now()}`,
      })
      const key = res.data.data.unikey
      const res2 = await this.axios({
        url: `http://localhost:3000/login/qr/create?key=${key}&qrimg=true&timerstamp=${Date.now()}`,
      })
      document.querySelector('#qrImg').src = res2.data.data.qrimg

      timer = setInterval(async () => {
        const statusRes = await this.checkStatus(key)
        if (statusRes.code === 800) {
          alert('二维码已过期,请重新获取')
          clearInterval(timer)
        }
        if (statusRes.code === 803) {
          // 这一步会返回cookie
          clearInterval(timer)
          alert('授权登录成功')
          await this.getLoginStatus(statusRes.cookie)
          localStorage.setItem('cookie', statusRes.cookie)
          this.$router.push({path: '/home'})
        }
      }, 3000)
    },
    create_erweima() {
      this.login()
    },
  },
  created() {
  },
  mounted() {
  },
}


</script>

<style scoped>
.logo {
  text-align: center;
  padding: 20px;
}

.logo > img {
  width: 70%;
}

.erweima {
  width: 60%;
  text-align: center;
  margin: auto;
  padding: 10px;
}
.rightb{
  padding-top: 20px;
}


</style>